layui.use(['form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    var catId = $("#catId").val();
    var status = $("#status").val();
    var searchType = $("#searchType").val();
    //列表
    var tableIns = table.render({
        elem: '#entityList',
        url : '/activity/jsonList',
        where: {status: status,searchType:searchType},
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limit : 20,
        method:'post',
        limits : [10,15,20,25,2000],
        id : "entityList",
        cols : [[
            {type:'checkbox'},
            {field: 'id',minWidth:120, title: 'id',align:'center'},
            {field: 'title',minWidth:120, title: '活动名称',align:'center'},
            {field: 'catName',minWidth:120, title: '分类名称',align:'center'},
            {field: 'status',minWidth:170, title: '状态', align:'center', templet:function(d){
                if(d.status=="1"){
                    return '<input class="editStatus" checked="true" data-id="'+d.id+'" name="open" lay-skin="switch" lay-filter="switchTest" lay-event="editStatus" type="checkbox">';
                }else{
                    return '<input class="editStatus" name="open" data-id="'+d.id+'" lay-skin="switch" lay-filter="switchTest" lay-event="editStatus" type="checkbox">';
                }
            }},
            {field: 'itemCountNum', title: '商品数',align:'center'},
            {field: 'priceRecord', title: '加价',align:'center'},
            {field: 'profitRecord', title: '利润',align:'center'},
            {field: 'keywordOne',minWidth:120, title: '关键字',align:'center'},
            {field: 'startTime',minWidth:120, title: '开始时间',align:'center'},
            {field: 'endTime',minWidth:120, title: '结束时间',align:'center'},
            {field: 'id',minWidth:120, title: '活动链接',align:'center', templet:function(d){
                    return '<input class="editStatus" type="text" value="/phone/activity/'+d.id+'?a=1">';
            }},
            {field: 'orderNum',minWidth:120, title: '排序',align:'center'},

            {field: 'createTime',minWidth:170, title: '创建时间', align:'center', templet:function(d){
                return d.createTime;
            }},
            {title: '操作',width:170,align:"center", templet:function(d){
                return '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>\
                         <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="list">商品</a>\
                    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>';
            }}
        ]]
    });

    //搜索
    $(".search_btn").on("click",function(){
        table.reload("entityList",{
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                status: $("#status").val(),
                searchType: $("#searchType").val(),
                title: $("#title").val()
            }
        })
    });

    $(".add_profit_price_cat_btn").click(function(){
        // 获取所有的ids
        var checkStatus = layui.table.checkStatus('entityList').data;

        if(checkStatus.length == 0){
            layer.alert("请选择至少一个品牌！")
            return false;
        }

        var ids = [];
        var activityIds = [];
        var flag = true;
        $.each(checkStatus,function(i,v){
            activityIds.push(v.id);
            ids.push(v.brandId);
            if (v.itemCountNum <= 0){
                flag = false;
                return false;
            }
        });
        if (!flag){
            layer.alert("您选择的活动中必须有商品！")
            return false;
        }
        // console.log(ids.join(","));
        var index = layui.layer.open({
            title :"品牌分类",
            type : 2,
            content : "/item/selectBrandProfitCatEntity?brandIds="+ids.join(",")+"&activityIds="+activityIds.join(","),
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                body.find(".closeLay").bind("click",function () {
                    layui.layer.close(index);
                })
                layui.layer.full(index);
            }
        });
    });

    $(".accept_btn").click(function(){
        layer.confirm('是否同步活动',{icon:3, title:'提示信息'},function(index){
            layer.close(index);
            var tishi = layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
            $.get("/activity/getDdcAcceptActivity","",function(result){
                layer.close(tishi);
                if(1==result.returnInfo.state){
                    tableIns.reload();
                }else{
                    top.layer.msg(result.returnInfo.errorMsg);
                }
            })
        });
    });

    $(".item_accept_btn").click(function(){
        // 获取所有的ids
        var checkStatus = layui.table.checkStatus('entityList').data;
        if(checkStatus.length == 0){
            layer.alert("请选择活动！")
            return false;
        }
        var ids = [];
        $.each(checkStatus,function(i,v){
            ids.push(v.id);
        });
        console.log(ids.join(","));
        layer.confirm('是否同步选中活动商品信息，将自动过滤已同步过活动',{icon:3, title:'提示信息'},function(index){
            layer.close(index);
            var tishi = layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
            $.get("/item/getDdcAcceptProduct",{activityIds:ids.join(",")},function(result){
                if(1==result.returnInfo.state){
                    tableIns.reload();
                    layer.close(tishi);
                }else{
                    top.layer.alert(result.returnInfo.errorMsg)
                    layer.close(tishi);
                }
            })
        });
    });

    //增加/编辑
    function addEntity(params){
        var title="编辑";
        var catId = $("#catId").val();
        if(params==null||params==""){
            title="添加"
            params = "?catId="+catId;
        }else {
            params = params + "&catId="+catId;
        }
        var index = layui.layer.open({
            title :title,
            type : 2,
            content : "/activity/selectEntity"+params,
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                body.find(".closeLay").bind("click",function () {
                    layui.layer.close(index);
                })
                layui.layer.full(index);
            }
        });
    }
    $(".add_btn").click(function(){
        addEntity('');
    })

    //列表操作
    table.on('tool(entityList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            addEntity("?id="+data.id);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('是否删除商品活动【'+data.title+'】吗？',{icon:3, title:'提示信息'},function(index){
                $.get("/activity/deleteEntity",{
                    "id":data.id,
                    "_method":"DELETE"
                },function(result){
                    if(1==result.returnInfo.state){
                        tableIns.reload();
                        layer.close(index);
                    }else{
                        top.layer.msg(result.returnInfo.errorMsg);
                    }
                })
            });
        } else if(layEvent === 'list'){
            window.location.href = "/activityItem/listPage"+"?activityId="+data.id;
        }
    });
// 主键
    form.on('switch(switchTest)', function(obj){
        // 获取当前控件
        var id = $(this).attr("data-id");
        console.log(id);
        var status = "2";
        if (this.checked){
            status = "1";
        }
        $.get("/activity/updateStatus",{
            "id":id,
            "status":status,
            "_method":"DELETE"
        },function(result){
            if(1==result.returnInfo.state){
                tableIns.reload();
            }else{
                top.layer.msg(result.returnInfo.errorMsg);
            }
        })
    });
})